package com.wyx.config.shiro;

import com.wyx.domain.User;
import com.wyx.service.UserService;
import com.wyx.vo.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.aspectj.util.GenericSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * @author xiaoxiong
 * @version 1.0
 * @date 2021/2/24 22:30
 * 自定义realm 去匹配用户名和密码
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做认证 就是登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 得到登陆的用户名
        String phone = token.getPrincipal().toString();
        User user = userService.queryUserByPhone(phone);
        if(user != null){
            // 用户存在判断密码
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            // 匹配密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    // ByteSource.Util.bytes(user.getSalt()) 获取盐
                    activerUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName()
            );
            return info;
        }else {
            // 用户不存在
            return null;
        }
    }
    
    /**
     * 做授权 登录成功过后判断用户是否拥有某个菜单或者按钮的权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ActiverUser activerUser =(ActiverUser) principalCollection.getPrimaryPrincipal();
        // 先默认返回一个info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }


}
